package com.qms.web.controller.system;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qms.common.core.controller.BaseController;
import com.qms.common.core.domain.AjaxResult;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 数据导入控制器
 * 
 * @author qms
 */
@RestController
@RequestMapping("/system/import")
public class SysImportController extends BaseController
{
    @Autowired
    private DataSource dataSource;

    /**
     * 导入证书表结构更新
     */
    @PreAuthorize("@ss.hasPermi('system:dict:list')")
    @GetMapping("/certificate-update")
    public AjaxResult importCertificateUpdate() throws SQLException, IOException
    {
        // 执行SQL文件
        try (Connection conn = dataSource.getConnection())
        {
            // 执行证书表结构更新脚本
            String alterScript = new String(Files.readAllBytes(Paths.get("../sql/certificate_type_validuntil_alter.sql")), StandardCharsets.UTF_8);
            ScriptUtils.executeSqlScript(conn, new org.springframework.core.io.ByteArrayResource(alterScript.getBytes()));
            
            // 执行字典数据脚本
            String dictScript = new String(Files.readAllBytes(Paths.get("../sql/certificate_dict_data.sql")), StandardCharsets.UTF_8);
            ScriptUtils.executeSqlScript(conn, new org.springframework.core.io.ByteArrayResource(dictScript.getBytes()));
            
            // 执行测试数据脚本
            String testDataScript = new String(Files.readAllBytes(Paths.get("../sql/certificate_test_data.sql")), StandardCharsets.UTF_8);
            ScriptUtils.executeSqlScript(conn, new org.springframework.core.io.ByteArrayResource(testDataScript.getBytes()));
            
            return success("证书表结构更新成功");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return error("证书表结构更新失败：" + e.getMessage());
        }
    }
} 